<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="900px" :title="`${drawerProps.title}列配置`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      label-position="left"
    >
      <!-- 基础配置 -->
      <el-form-item label="分类" prop="category">
        <el-select v-model="drawerProps.row!.category" placeholder="请选择分类" clearable>
          <el-option v-for="type in categoryOptions" :key="type" :label="type" :value="type" />
        </el-select>
      </el-form-item>
      <el-form-item label="列名" prop="label">
        <el-input v-model="drawerProps.row!.label" placeholder="请输入列名" clearable></el-input>
      </el-form-item>
      <el-form-item label="字段名(key)" prop="key">
        <el-input v-model="drawerProps.row!.key" placeholder="请输入字段名" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色权限" prop="permission">
        <el-select
          v-model="drawerProps.row!.permission"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择或输入角色权限"
          style="width: 100%"
        >
          <el-option v-for="item in permissionOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据类型" prop="renderType">
        <el-select v-model="drawerProps.row!.renderType" placeholder="请选择数据类型" clearable @change="handleTypeChange">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="宽度" prop="width">
        <el-input-number v-model="drawerProps.row.width" :min="50" :max="500" placeholder="请输入宽度"></el-input-number>
      </el-form-item>
      <!-- 仅在renderType为text、strArr、textarea时显示占位模板 -->
      <el-form-item
        v-if="
          drawerProps.row!.renderType === 'text' ||
          drawerProps.row!.renderType === 'strArr' ||
          drawerProps.row!.renderType === 'textarea'
        "
        label="占位模板"
        prop="placeholderTemplate"
      >
        <el-input v-model="drawerProps.row.placeholderTemplate" placeholder="请输入占位模板"></el-input>
      </el-form-item>

      <!--仅在renderType为number时显示单位配置 -->
      <el-form-item v-if="drawerProps.row!.renderType === 'number'" label="单位" prop="unit">
        <el-input v-model="drawerProps.row.unit" placeholder="请输入单位，如：元、kg、个等"></el-input>
      </el-form-item>

      <!-- 表单配置（对象数组类型时显示） -->
      <el-form-item v-if="drawerProps.row!.renderType === 'objArr'" label="表单配置" prop="formConfig">
        <div class="form-config-container">
          <el-table :data="formConfigFields" border style="width: 100%">
            <el-table-column prop="key" label="字段名" width="120" align="center">
              <template #default="{ row }">
                <el-input v-model="row.key" placeholder="如：username"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="label" label="显示名" width="120" align="center">
              <template #default="{ row }">
                <el-input v-model="row.label" placeholder="如：用户名"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="required" label="必填" width="80" align="center">
              <template #default="{ row }">
                <el-checkbox v-model="row.required"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="inputType" label="输入类型" width="140" align="center">
              <template #default="{ row }">
                <el-select v-model="row.inputType" placeholder="选择类型" clearable>
                  <el-option v-for="type in inputTypeOptions" :key="type" :label="type" :value="type" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="placeholderTemplate" label="占位模板" width="200" align="center">
              <template #default="{ row }">
                <el-input v-model="row.placeholderTemplate" placeholder="如：请输入{{label}}" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="{ $index }">
                <el-button type="danger" size="small" @click="removeFormConfigField($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="mt-10" type="primary" size="small" @click="addFormConfigField">新增字段</el-button>
        </div>
      </el-form-item>

      <!-- 显示字段选择 -->
      <el-form-item label="表格显示字段" prop="displayField">
        <el-select
          v-model="displayFieldSelected"
          multiple
          filterable
          :disabled="drawerProps.row!.renderType !== 'objArr'"
          placeholder="请选择要显示的字段"
          style="width: 100%"
        >
          <el-option v-for="field in formConfigFields" :key="field.key" :label="field.label || field.key" :value="field.key" />
        </el-select>
      </el-form-item>

      <!-- 其他配置 -->
      <el-form-item label="是否必填" prop="required">
        <el-switch v-model="drawerProps.row!.required" active-text="是" inactive-text="否" />
      </el-form-item>
      <el-form-item label="是否显示" prop="isShow">
        <el-switch v-model="drawerProps.row!.isShow" active-text="是" inactive-text="否" />
      </el-form-item>
      <el-form-item label="是否可排序" prop="sortable">
        <el-switch v-model="drawerProps.row!.sortable" active-text="是" inactive-text="否" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Column } from "@/api/interface/tableMange";

// 常量定义
const typeOptions = [
  { value: "text", label: "text" },
  { value: "img", label: "img" },
  { value: "strArr", label: "array" },
  { value: "objArr", label: "ObjArray" },
  { value: "number", label: "number" },
  { value: "textarea", label: "textarea" }
];

const inputTypeOptions = ["text", "number", "textarea"];
const categoryOptions = ["基础信息", "上下游信息", "联系人信息", "经营信息", "详细信息"];
const permissionOptions = ["admin", "user"];

// 表单数据
const formConfigFields = ref<
  Array<{
    key: string;
    label: string;
    required: boolean;
    inputType: string;
    placeholderTemplate?: string;
    unit?: string;
  }>
>([]);

const displayFieldSelected = ref<string[]>([]);
const drawerVisible = ref(false);
const ruleFormRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive({
  category: [{ required: true, message: "请输入类别" }],
  label: [{ required: true, message: "请输入列名" }],
  key: [{ required: true, message: "请输入字段名" }],
  renderType: [{ required: true, message: "请选择数据类型" }],
  permission: [{ required: true, message: "请选择角色权限" }],
  formConfig: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (drawerProps.value.row?.renderType === "objArr" && formConfigFields.value.length === 0) {
          callback(new Error("请至少配置一个表单字段"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  displayField: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (drawerProps.value.row?.renderType === "objArr" && displayFieldSelected.value.length === 0) {
          callback(new Error("请至少选择一个显示字段"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  // 新增：单位配置的验证规则
  unit: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (drawerProps.value.row?.renderType === "number" && !value) {
          callback(new Error("请输入单位"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

// 抽屉组件属性
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Column.ResColumnList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 添加表单字段
const addFormConfigField = () => {
  formConfigFields.value.push({
    key: "",
    label: "",
    required: false,
    inputType: "text",
    placeholderTemplate: "",
    unit: ""
  });
};

// 删除表单字段
const removeFormConfigField = (index: number) => {
  const removedField = formConfigFields.value[index];
  formConfigFields.value.splice(index, 1);
  displayFieldSelected.value = displayFieldSelected.value.filter(field => field !== removedField.key);
};

// 数据类型变化处理
const handleTypeChange = (value: string) => {
  console.log(value);

  if (value !== "objArr") {
    formConfigFields.value = [];
    displayFieldSelected.value = [];
  }
  // 清除非文字输入类型的占位模板
  if (value === "img") {
    drawerProps.value.row!.placeholderTemplate = "";
  }
  if (value === "number") {
    drawerProps.value.row!.placeholderTemplate = "";
  }
  // 清除非number类型的单位配置
  if (value !== "number") {
    drawerProps.value.row!.unit = "";
  }
};

// 显示字段选择变化监听
watch(displayFieldSelected, newVal => {
  drawerProps.value.row!.displayField = newVal.join(",");
});

// 接收父组件参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = {
    ...params,
    row: {
      ...params.row,
      width: Number(params.row.width) || 100,
      // 如果renderType不是text或者strArr、textarea，清空placeholderTemplate
      placeholderTemplate:
        params.row.renderType === "text" || params.row.renderType === "strArr" || params.row.renderType === "textarea"
          ? params.row.placeholderTemplate
          : "",
      // 设置number类型的单位
      unit: params.row.renderType === "number" ? params.row.unit || "" : "",
      isShow: params.row.isShow ? true : false,
      required: params.row.required ? true : false,
      sortable: params.row.sortable ? true : false,
      category: params.row.category || "基础信息",
      key: params.row.key || "",
      renderType: params.row.renderType || "text",
      label: params.row.label || ""
    }
  };

  // 处理权限字段
  if (drawerProps.value.row.permission && typeof drawerProps.value.row.permission === "string") {
    drawerProps.value.row.permission = drawerProps.value.row.permission.split(",").filter(item => item.trim() !== "");
  } else if (!drawerProps.value.row.permission) {
    drawerProps.value.row.permission = ["admin"];
  }

  // 初始化表单配置
  formConfigFields.value = [];
  displayFieldSelected.value = [];

  if (drawerProps.value.row.renderType === "objArr" && drawerProps.value.row.formConfig) {
    try {
      const config =
        typeof drawerProps.value.row.formConfig === "string"
          ? JSON.parse(drawerProps.value.row.formConfig)
          : drawerProps.value.row.formConfig;

      formConfigFields.value = (Array.isArray(config) ? config : []).map(item => ({
        key: item.key || "",
        label: item.label || "",
        required: item.required === true || item.required == "true" || false,
        inputType: item.inputType || "text",
        placeholderTemplate: item.placeholderTemplate || "",
        unit: item.inputType === "number" ? item.unit || "" : ""
      }));
    } catch (e) {
      console.error("表单配置解析失败:", e);
    }
  }

  // 初始化显示字段
  if (drawerProps.value.row.displayField) {
    displayFieldSelected.value =
      typeof drawerProps.value.row.displayField === "string"
        ? drawerProps.value.row.displayField.split(",").filter(item => item.trim() !== "")
        : [...drawerProps.value.row.displayField];
  }

  drawerVisible.value = true;
};

// 提交表单
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      // 创建基础提交数据，包含必填字段
      const submitData: Record<string, any> = {
        ...drawerProps.value.row
      };

      // 处理权限字段
      if (drawerProps.value.row.permission) {
        submitData.permission = Array.isArray(drawerProps.value.row.permission)
          ? drawerProps.value.row.permission.join(",")
          : drawerProps.value.row.permission;
      }

      // 处理 objArr 类型的表单配置
      if (drawerProps.value.row.renderType === "objArr") {
        const formattedFields = formConfigFields.value.map(field => {
          const fieldCopy = { ...field };
          // 非数字类型字段移除单位配置
          if (field.inputType !== "number") {
            delete fieldCopy.unit;
          }
          return fieldCopy;
        });

        // 只有存在配置字段时才添加 formConfig
        if (formattedFields.length > 0) {
          submitData.formConfig = formattedFields;
        }
      }

      // 处理 objArr 类型的显示字段
      if (drawerProps.value.row.renderType === "objArr" && displayFieldSelected.value?.length > 0) {
        submitData.displayField = displayFieldSelected.value.join(",");
      } else {
        submitData.displayField = submitData.key;
      }

      // 处理 text和strArr 类型的占位符模板
      if (
        (drawerProps.value.row.renderType === "text" ||
          drawerProps.value.row.renderType === "strArr" ||
          drawerProps.value.row.renderType === "textarea") &&
        drawerProps.value.row.placeholderTemplate
      ) {
        submitData.placeholderTemplate = drawerProps.value.row.placeholderTemplate;
      }

      // 处理 number 类型的单位配置
      if (drawerProps.value.row.renderType === "number" && drawerProps.value.row.unit) {
        submitData.unit = drawerProps.value.row.unit;
      }
      await drawerProps.value.api!(submitData);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.error("提交失败:", error);
      ElMessage.error("提交失败，请重试");
    }
  });
};

defineExpose({ acceptParams });
</script>

<style scoped>
/* 表格全局居中 */
:deep(.el-table th > .cell),
:deep(.el-table td > .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 表格内输入框样式 */
:deep(.el-table .el-input),
:deep(.el-table .el-select) {
  width: 95%;
}
.form-config-container {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.mt-10 {
  margin-top: 10px;
}
</style>
